import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:provider/provider.dart';
import 'package:blurb/common/store/user_store.dart';
import 'package:go_router/go_router.dart';

class InformationPage extends StatefulWidget {
  const InformationPage({super.key});

  @override
  State<InformationPage> createState() => _InformationPageState();
}

class _InformationPageState extends State<InformationPage> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _signController = TextEditingController();
  String? _selectedAvatarPath;
  late UserStore _userStore;

  @override
  void initState() {
    super.initState();
    // 直接获取UserStore，而不是通过StoreProvider
    _userStore = Provider.of<UserStore>(context, listen: false);
    
    // 初始化控制器
    if (_userStore.currentUser != null) {
      _nameController.text = _userStore.currentUser!.nickname;
      _signController.text = _userStore.currentUser!.sign;
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _signController.dispose();
    super.dispose();
  }

  // 选择头像
  Future<void> _selectAvatar() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: const AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
      ),
    );

    if (result != null && result.isNotEmpty) {
      final file = await result[0].file;
      if (file != null) {
        setState(() {
          _selectedAvatarPath = file.path;
        });
      }
    }
  }

  // 保存用户信息
  Future<void> _saveUserInfo() async {
    final success = await _userStore.updateUserInfo(
      nickname: _nameController.text,
      avatar: _selectedAvatarPath ?? _userStore.currentUser?.avatar,
      sign: _signController.text,
    );

    if (success && mounted) {
      context.pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // 标题栏
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
              child: Stack(
                alignment: Alignment.center,
                children: [
                  // 居中标题
                  Align(
                    alignment: Alignment.center,
                    child: Text(
                      'Modify information',
                      style: GoogleFonts.racingSansOne(
                        color: Colors.white,
                        fontSize: 20.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  // 左侧返回按钮
                  Align(
                    alignment: Alignment.centerLeft,
                    child: GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Icon(Icons.arrow_back_ios, color: Colors.white),
                    ),
                  ),
                ],
              ),
            ),
            
            // 内容区域
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SizedBox(height: 30.h),
                      
                      // 头像选择
                      GestureDetector(
                        onTap: _selectAvatar,
                        child: Stack(
                          alignment: Alignment.bottomRight,
                          children: [
                            Container(
                              width: 120.w,
                              height: 120.w,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                image: DecorationImage(
                                  image: _selectedAvatarPath != null
                                      ? FileImage(File(_selectedAvatarPath!))
                                      : _userStore.currentUser?.avatar != null
                                          ? AssetImage(_userStore.currentUser!.avatar) as ImageProvider
                                          : const AssetImage('assets/images/avatar.png'),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.all(8.w),
                              decoration: const BoxDecoration(
                                shape: BoxShape.circle,
                                color: Colors.blue,
                              ),
                              child: const Icon(
                                Icons.camera_alt,
                                color: Colors.white,
                                size: 20,
                              ),
                            ),
                          ],
                        ),
                      ),
                      
                      SizedBox(height: 50.h),
                      
                      // 昵称输入
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Name',
                            style: GoogleFonts.racingSansOne(
                              color: Colors.white,
                              fontSize: 16.sp,
                            ),
                          ),
                          SizedBox(height: 10.h),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 15.w),
                            decoration: BoxDecoration(
                              color: Colors.grey[900],
                              borderRadius: BorderRadius.circular(10.r),
                            ),
                            child: TextField(
                              controller: _nameController,
                              style: const TextStyle(color: Colors.white),
                              decoration: const InputDecoration(
                                border: InputBorder.none,
                                hintText: 'Enter your name',
                                hintStyle: TextStyle(color: Colors.grey),
                              ),
                            ),
                          ),
                        ],
                      ),
                      
                      SizedBox(height: 30.h),
                      
                      // 签名输入
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Sign',
                            style: GoogleFonts.racingSansOne(
                              color: Colors.white,
                              fontSize: 16.sp,
                            ),
                          ),
                          SizedBox(height: 10.h),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 15.w),
                            decoration: BoxDecoration(
                              color: Colors.grey[900],
                              borderRadius: BorderRadius.circular(10.r),
                            ),
                            child: TextField(
                              controller: _signController,
                              style: const TextStyle(color: Colors.white),
                              maxLines: 3,
                              decoration: const InputDecoration(
                                border: InputBorder.none,
                                hintText: 'Enter your sign',
                                hintStyle: TextStyle(color: Colors.grey),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            // 确认按钮
            Padding(
              padding: EdgeInsets.all(20.w),
              child: GestureDetector(
                onTap: _saveUserInfo,
                child: Container(
                  width: double.infinity,
                  height: 50.h,
                  decoration: BoxDecoration(
                    color: const Color(0xFF64B5F6),
                    borderRadius: BorderRadius.circular(25.r),
                  ),
                  alignment: Alignment.center,
                  child: Text(
                    'confirm',
                    style: GoogleFonts.racingSansOne(
                      color: Colors.white,
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}